package com.simtop.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.simtop.common.Key;
import com.simtop.common.ServerResponse;
import com.simtop.dao.RobotStepScoreDao;
import com.simtop.dao.U3DRobotDao;
import com.simtop.dao.UserDao;
import com.simtop.pojo.*;
import com.simtop.pojo.ilabresult.IlabSport;
import com.simtop.pojo.ilabresult.Step;
import com.simtop.pojo.newrequire.RobotStepScore;
import com.simtop.service.U3DRobotService;
import com.simtop.util.PostUtil;
import com.simtop.util.VideoUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;

@Service
public class U3DRobotServiceImpl implements U3DRobotService {

    private static final Logger logger = LoggerFactory.getLogger(U3DRobotServiceImpl.class);

    @Autowired
    private U3DRobotDao u3DRobotDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private RobotStepScoreDao robotStepScoreDao;

    @Override
    public ServerResponse<String> add(Robot1 robot, User user) {
        IlabSport ilabSport = robot.getIlabSport();
        if(null!=user.getAccessToken()){
            /**
             * 获取上传ilab的成绩
             */
            ilabSport.setTitle("大型钢结构多机器人协同焊接控制虚拟仿真实验");
            ilabSport.setAppid((int)Key.issuerId);
            ilabSport.setUsername(user.getLoginName());
            ilabSport.setOriginId(UUID.randomUUID().toString().replaceAll("-","_"));
            String json= JSONObject.toJSONString(ilabSport);
            System.out.println("json="+json);
            try {
                String code= PostUtil.post(user.getAccessToken(),json,"application/json");
                System.out.println("调用实验结果接口的返回码==================" + code);
                JSONObject jsonObject= JSON.parseObject(code);
                if(jsonObject.getInteger("code")!=0){
                    Operate operate = new Operate("ilab用户提交成绩",user.getUsername(),"传输记录失败，请检查",null,robot+"",user.getRoleId());
                    userDao.insertOperate(operate);
                    return ServerResponse.createByErrorMsg("数据插入失败！");
                }else{
                    Operate operate = new Operate("ilab用户提交成绩",user.getUsername(),"传输记录成功",null,robot+"",user.getRoleId());
                    userDao.insertOperate(operate);
                }
            } catch (Exception e) {
                e.printStackTrace();
                Operate operate = new Operate("ilab用户提交成绩",user.getUsername(),"传输记录失败，请检查",null,robot+"",user.getRoleId());
                userDao.insertOperate(operate);
                return ServerResponse.createByErrorMsg("数据插入失败！");
            }
        }
        /**
         * 定义成绩实体
         */
        RobotStepScore robotStepScore = new RobotStepScore();
        robotStepScore.setStepScore(JSONObject.toJSONString(ilabSport.getSteps()));
        robotStepScore.setUserId(user.getId());
        robotStepScore.setUseTime(VideoUtil.secToTime((int)(ilabSport.getEndTime()-ilabSport.getStartTime())/1000));
        robotStepScore.setTotalScore(ilabSport.getScore());
        robotStepScore.setConclusion(robot.getConclusion());
        robotStepScore.setStar(robot.getStar());
        User user1 = userDao.checkLoginNameOrEmail(user.getLoginName(), null);
        robotStepScore.setExercises(user1.getExercises());
        boolean b = robotStepScoreDao.insertScore(robotStepScore);
        if (!b){
            Operate operate = new Operate("用户提交成绩",user.getUsername(),"传输记录失败，请检查",null,robot+"",user.getRoleId());
            userDao.insertOperate(operate);
            return ServerResponse.createByErrorMsg("传输记录失败，请检查");
        }
        /*RobotResult robotResult=new RobotResult();
        robotResult.setId(robot.getId());
        robotResult.setName(robot.getName());
        robotResult.setScene(robot.getScene());
        robotResult.setWiring(robot.getWiring());
        robotResult.setProgramming(robot.getProgramming());
        robotResult.setExample(robot.getExample());
        robotResult.setTotal(robot.getTotal());
        robotResult.setConclusion(robot.getConclusion());
        robotResult.setTime(VideoUtil.secToTime(robot.getTime()));
        robotResult.setStar(robot.getStar());
        robotResult.setIoScore(robot.getIoScore());
        robotResult.setIoTime(VideoUtil.secToTime(robot.getIoTime()));
        robotResult.setExperimentScore(robot.getExperimentScore());
        robotResult.setExperimentTime(VideoUtil.secToTime(robot.getExperimentTime()));
        robotResult.setTechnologyScore(robot.getTechnologyScore());
        robotResult.setTechnologyTime(VideoUtil.secToTime(robot.getTechnologyTime()));
        robotResult.setSystemScore(robot.getSystemScore());
        robotResult.setSystemTime(VideoUtil.secToTime(robot.getSystemTime()));
        robotResult.setCommunicationScore(robot.getCommunicationScore());
        robotResult.setCommunicationTime(VideoUtil.secToTime(robot.getCommunicationTime()));
        robotResult.setPrincipalIoScore(robot.getPrincipalIoScore());
        robotResult.setPrincipalIoTime(VideoUtil.secToTime(robot.getPrincipalIoTime()));
        robotResult.setCooperativeControlScore(robot.getCooperativeControlScore());
        robotResult.setCooperativeControlTime(VideoUtil.secToTime(robot.getCooperativeControlTime()));
        robotResult.setCollaborativeWeldingScore(robot.getCollaborativeWeldingScore());
        robotResult.setCollaborativeWeldingTime(VideoUtil.secToTime(robot.getCollaborativeWeldingTime()));
        robotResult.setSteelWeldingScore(robot.getSteelWeldingScore());
        robotResult.setSteelWeldingTime(VideoUtil.secToTime(robot.getSteelWeldingTime()));
        robotResult.setUserId(user.getId());
        robotResult.setName(user.getUsername());
        int  resultCount = u3DRobotDao.add(robotResult);
        if (resultCount != 1){
            Operate operate = new Operate("用户提交成绩",user.getUsername(),"传输记录失败，请检查",null,robot+"",user.getRoleId());
            userDao.insertOperate(operate);
            return ServerResponse.createByErrorMsg("传输记录失败，请检查");
        }*/
        Operate operate = new Operate("用户提交成绩",user.getUsername(),"传输记录成功",null,robot+"",user.getRoleId());
        userDao.insertOperate(operate);
        logger.info("U3DRobot："+robot);
        logger.info("实验id为"+robot.getId()+"的记录成功");
        return ServerResponse.createBySuccessMsg("传输记录成功");
    }

    @Override
    public ServerResponse<PageInfo<RobotResult>> findById(Integer id, User user, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<RobotResult> robot = u3DRobotDao.findById(id,user.getRoleId(),user.getId());
        PageInfo<RobotResult> robotPageInfo = new PageInfo<>(robot);
        if (robot == null){
            return ServerResponse.createByErrorMsg("找不到记录");
        }
        return ServerResponse.createBySuccess(robotPageInfo);
    }

    @Override
    public ServerResponse<PageInfo<Robot>> findResult(int pageNum, int pageSize,User user) {
        PageHelper.startPage(pageNum,pageSize);
        List<Robot> robots = u3DRobotDao.findResult(user);
        PageInfo<Robot> robotPageInfo = new PageInfo<>(robots);
        return ServerResponse.createBySuccess(robotPageInfo);
    }

    @Override
    public ServerResponse<String> deleteById(int id) {
        int count = u3DRobotDao.deleteById(id);
        if (count != 1){
            return ServerResponse.createByErrorMsg("删除失败");
        }
        return ServerResponse.createBySuccessMsg("删除成功");
    }

    @Override
    public ServerResponse<PageInfo<Robot>> findByName(String name, int pageNum, int pageSize) {
        String username = u3DRobotDao.findName(name);
        PageHelper.startPage(pageNum,pageSize);
        List<Robot> robots = u3DRobotDao.findByName(username);
        PageInfo<Robot> robotPageInfo = new PageInfo<>(robots);
        return ServerResponse.createBySuccess(robotPageInfo);
    }

    @Override
    public ServerResponse<Integer> findUserAccount() {
        return ServerResponse.createBySuccess(Integer.valueOf(u3DRobotDao.findUserAccount()));
    }

    @Override
    public ServerResponse<Integer> expAcct() {
        /**
         * 旧实验表的总条数
         */
        Integer count = Integer.valueOf(u3DRobotDao.expAcct());
        /**
         * 新实验表的总条数
         */
        Integer count1 = robotStepScoreDao.getCount();
        return ServerResponse.createBySuccess(count + count1);
    }

    @Override
    public ServerResponse<Integer> expTime() {
        /**
         * 旧的实验表总时间
         */
        List<RobotResult> robotResultList=u3DRobotDao.expTime();
        long time=0;
        for (int i = 0; i < robotResultList.size(); i++) {
            RobotResult robotResult=robotResultList.get(i);
            String[] times=robotResult.getTime().split(":");
            int num=1;
            for (int j = times.length-1; j >=0; j--) {
                time += Integer.parseInt(times[j])*num;
                num=num*60;
            }
        }
        /**
         * 新实验表总时间
         */
        List<RobotStepScore> robotStepScore = robotStepScoreDao.getTime();
        long time1 = 0;
        for(int i=0; i<robotStepScore.size(); i++){
            RobotStepScore robotStepScore1 = robotStepScore.get(i);
            String[] times=robotStepScore1.getUseTime().split(":");
            int num=1;
            for (int j = times.length-1; j >=0; j--) {
                time1 += Integer.parseInt(times[j])*num;
                num=num*60;
            }
        }
        return ServerResponse.createBySuccess(Math.round((time+time1)/ 60L));
    }

    @Override
    public ServerResponse addCommitScore(Integer id, Integer commitScore,String evaluation) {
        Integer addCommitScoreStatus=u3DRobotDao.addCommitScore(id,commitScore,evaluation);
        if(addCommitScoreStatus!=0){
            return ServerResponse.createBySuccessMsg("评分成功");
        }else{
            return ServerResponse.createByErrorMsg("评分失败");
        }
    }
}
